'use client';

import React, { useState } from 'react';
import { 
  ChevronDown, 
  ChevronRight, 
  Clock, 
  Tool, 
  FileText, 
  User, 
  Bot,
  Copy,
  Check
} from 'lucide-react';
import { ExecutionStep } from '@/types';
import { formatTimestamp } from '@/utils/formatTrace';

interface StepCardProps {
  step: ExecutionStep & { duration?: number };
  index: number;
  isExpanded?: boolean;
  onToggle?: () => void;
}

export default function StepCard({ 
  step, 
  index, 
  isExpanded = false, 
  onToggle 
}: StepCardProps) {
  const [copiedField, setCopiedField] = useState<string | null>(null);

  const copyToClipboard = async (text: string, field: string) => {
    try {
      await navigator.clipboard.writeText(text);
      setCopiedField(field);
      setTimeout(() => setCopiedField(null), 2000);
    } catch (err) {
      console.error('复制失败:', err);
    }
  };

  const CopyButton = ({ text, field }: { text: string; field: string }) => (
    <button
      onClick={() => copyToClipboard(text, field)}
      className="p-1 text-gray-400 hover:text-gray-600 transition-colors"
      title="复制"
    >
      {copiedField === field ? (
        <Check className="w-3 h-3" />
      ) : (
        <Copy className="w-3 h-3" />
      )}
    </button>
  );

  return (
    <div className="bg-white rounded-lg border border-gray-200 shadow-sm">
      {/* 步骤头部 */}
      <div 
        className="flex items-center justify-between p-4 cursor-pointer hover:bg-gray-50 transition-colors"
        onClick={onToggle}
      >
        <div className="flex items-center space-x-3">
          <div className="flex items-center space-x-2">
            {onToggle && (
              isExpanded ? (
                <ChevronDown className="w-4 h-4 text-gray-500" />
              ) : (
                <ChevronRight className="w-4 h-4 text-gray-500" />
              )
            )}
            <div className="w-8 h-8 bg-primary-100 text-primary-600 rounded-full flex items-center justify-center text-sm font-medium">
              {index + 1}
            </div>
          </div>
          
          <div>
            <h3 className="font-medium text-gray-900">{step.nodeName}</h3>
            <p className="text-sm text-gray-500">{step.agentName}</p>
          </div>
        </div>

        <div className="flex items-center space-x-4 text-sm text-gray-500">
          {step.duration !== undefined && (
            <div className="flex items-center space-x-1">
              <Clock className="w-4 h-4" />
              <span>{step.duration}ms</span>
            </div>
          )}
          <span>{formatTimestamp(step.timestamp)}</span>
        </div>
      </div>

      {/* 步骤详情 */}
      {isExpanded && (
        <div className="border-t border-gray-200 p-4 space-y-4">
          {/* 输入 */}
          <div>
            <div className="flex items-center justify-between mb-2">
              <h4 className="text-sm font-medium text-gray-700 flex items-center space-x-1">
                <User className="w-4 h-4" />
                <span>输入</span>
              </h4>
              <CopyButton text={step.input} field={`input-${index}`} />
            </div>
            <div className="bg-gray-50 rounded-md p-3 text-sm text-gray-800 whitespace-pre-wrap">
              {step.input}
            </div>
          </div>

          {/* 输出 */}
          <div>
            <div className="flex items-center justify-between mb-2">
              <h4 className="text-sm font-medium text-gray-700 flex items-center space-x-1">
                <Bot className="w-4 h-4" />
                <span>输出</span>
              </h4>
              <CopyButton text={step.output} field={`output-${index}`} />
            </div>
            <div className="bg-blue-50 rounded-md p-3 text-sm text-gray-800 whitespace-pre-wrap">
              {step.output}
            </div>
          </div>

          {/* 工具调用 */}
          {step.usedTools && step.usedTools.length > 0 && (
            <div>
              <h4 className="text-sm font-medium text-gray-700 flex items-center space-x-1 mb-2">
                <Tool className="w-4 h-4" />
                <span>工具调用 ({step.usedTools.length})</span>
              </h4>
              <div className="space-y-2">
                {step.usedTools.map((tool, toolIndex) => (
                  <div key={toolIndex} className="bg-yellow-50 rounded-md p-3">
                    <div className="font-medium text-sm text-yellow-800 mb-1">
                      {tool.tool}
                    </div>
                    <div className="text-xs text-gray-600 space-y-1">
                      <div>
                        <span className="font-medium">输入:</span>
                        <pre className="mt-1 text-xs bg-white p-2 rounded border overflow-x-auto">
                          {JSON.stringify(tool.toolInput, null, 2)}
                        </pre>
                      </div>
                      <div>
                        <span className="font-medium">输出:</span>
                        <pre className="mt-1 text-xs bg-white p-2 rounded border overflow-x-auto">
                          {JSON.stringify(tool.toolOutput, null, 2)}
                        </pre>
                      </div>
                    </div>
                  </div>
                ))}
              </div>
            </div>
          )}

          {/* 源文档 */}
          {step.sourceDocuments && step.sourceDocuments.length > 0 && (
            <div>
              <h4 className="text-sm font-medium text-gray-700 flex items-center space-x-1 mb-2">
                <FileText className="w-4 h-4" />
                <span>源文档 ({step.sourceDocuments.length})</span>
              </h4>
              <div className="space-y-2">
                {step.sourceDocuments.map((doc, docIndex) => (
                  <div key={docIndex} className="bg-green-50 rounded-md p-3">
                    <div className="text-sm text-gray-800">
                      {typeof doc === 'string' ? doc : JSON.stringify(doc, null, 2)}
                    </div>
                  </div>
                ))}
              </div>
            </div>
          )}
        </div>
      )}
    </div>
  );
}
